<?php
namespace App\Controllers;

/**
 * Class BaseController
 *
 * BaseController provides a convenient place for loading components
 * and performing functions that are needed by all your controllers.
 * Extend this class in any new controllers:
 *     class Home extends BaseController
 *
 * For security be sure to declare any new methods as protected or private.
 *
 * @package CodeIgniter
 */

use App\Controllers\BaseController;
use App\Models\AdminModel;
use App\Models\RbacModel;

class AdminBase extends BaseController
{
    /**
     * An array of helpers to be loaded automatically upon
     * class instantiation. These helpers will be available
     * to all other controllers that extend BaseController.
     *
     * @var array
     */
    // protected $helpers = [];

    public $adminid;
    public $admin;
    public $mod;

    protected $adminModel;
    protected $rbacModel;

    /**
     * Constructor.
     */
    public function initController($request, $response, $logger)
    {
        // Do Not Edit This Line
        parent::initController($request, $response, $logger);

        define('IS_ADMIN', 1);

        $this->adminModel = new AdminModel();
        $this->rbacModel = new RbacModel();

        \CodeIgniter\Events\Events::trigger('ciams_adminbase_init_before');

        //登录判断
        $this->admin = $this->is_admin_login();

        if ((!$this->adminid || !$this->admin) && (!isset($this->uri[1]) || (isset($this->uri[1]) && $this->uri[1] != 'login'))) {

            $hashcode = $this->request->getGet('hashcode', FILTER_SANITIZE_STRING);
            if (!SITE_ADMIN_HASHCODE || !$hashcode || $hashcode != SITE_ADMIN_HASHCODE) {
                $this->goTo404('页面未找到1');
                exit();
            }

            if (!isset($this->uri[1]) || (isset($this->uri[1]) && $this->uri[1] != 'login')) {
                $this->adminMsg(1, '请登录', ['url' => url('admin/login/index', ['hashcode' => $hashcode, 'backurl' => MOK_NOW_URL])]);
            }
        }

        // 权限判断
        if (($this->uri[0] == 'admin' && (isset($this->uri[1]) && $this->uri[1] != 'login') && !$this->is_auth($this->uri)) && $this->adminid != 1) {
            $this->adminMsg(1, '您无权限操作', ['url' => $this->uri]);
        }

        $this->renderer->setData(['admin' => $this->admin]);

        \CodeIgniter\Events\Events::trigger('ciams_adminbase_init_after');
    }

    //是否登陆
    protected function is_admin_login()
    {
        if (IS_ADMIN && isset($this->uri[1]) && $this->uri[1] == 'login') {
            return false;
        }

        $adminid = get_cookie('adminid');
        if ($adminid) {
            $admin = $this->adminModel->get($adminid);
            if (!$admin) {
                return false;
            }
            if(!$this->adminModel->check_admin_cookie($admin)){
                return false;
            }
        }else{
            return false;
        }

        $this->admin = $admin;
        $this->adminid = $adminid;
        return $this->admin;
    }

    //提示消息
    public function adminMsg($code, $msg, $data = [])
    {
        $backurl = ''; //跳转的地址
        $time = isset($data['time']) ? intval($data['time']) : 0; //默认3秒跳转

        if (isset($data['url']) && $data['url']) {
            $backurl = $this->xss_clean($data['url']);
            if (strpos($backurl, '?backurl=') !== false) {
                $arr = explode('?backurl=', $backurl);
                if (isset($arr[1]) && $arr[1]) {
                    $backurl = $arr[0] . '?backurl=' . urlencode($arr[1]);
                }
            }
        } else if (isset($_SERVER['HTTP_REFERER']) && strpos($_SERVER['HTTP_REFERER'], 'php?') !== false) {
            $backurl = $this->xss_clean($_SERVER['HTTP_REFERER']);
        } else if (!$backurl) {
            $backurl = SELF;
        }
        if ($this->request->getGet('is_ajax') || IS_AJAX || $this->request->isAJAX()) {
            exit($this->_json($code, $msg));
        }
        $vdata = [
            'code' => $code,
            'msg' => $msg,
            'url' => $backurl,
            'time' => $time,
            'mark' => $code,
        ];
        echo view('msg.html', $vdata);
        exit();
    }

    protected function is_auth($uri = '')
    {
        if (!$uri || $this->admin['roleid'] == 1) {
            return true;
        }
        if (is_array($uri)) {
            $uri = implode('/', $uri);
        }
        //忽略验证
        $skip = [
            'admin/home/index',
            'admin/home/main',
        ];
        $auth = $this->rbacModel->getRoleAuth($this->admin);
        if (!in_array($uri, $auth) && !in_array($uri, $skip)) {
            $this->adminMsg(1, '您还没有权限(' . $uri . ')', ['url' => url('admin/home/main')]);
        }
        return true;
    }

    /**
     * 后台日志
     */
    protected function addSystemLog($action, $admin = [])
    {
        $admin = $this->admin;
        $logarr = ['action' => $action, 'userid' => $admin['userid'] ?? 0, 'username' => $admin['username'] ?? ''];
        $this->systemModel->insterLog($logarr);
    }

    protected function getMod()
    {
        $mod = $this->request->getGet('mod');
        ams_clean_xss($mod);
        $this->mod = $mod;
        return $mod;
    }

}
